<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container">
      <el-input v-model="listQuery.loginname" placeholder="登录名" size="small" style="width: 200px; " class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.name" placeholder="姓名" size="small" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item"  size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;"  size="small" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" size="small" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      :height="tableHeight"
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.loginname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.rolenames }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.deleteflag_Str }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册日期" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createdate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="250">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-popconfirm
            title="确认删除吗？"
            @onConfirm="handleDelete(row, $index)"
          >
            <el-button slot="reference" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名" prop="title">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="登录名" prop="title">
          <el-input v-model="temp.loginname" />
        </el-form-item>
        <el-form-item label="密码" prop="title">
          <el-input v-model="temp.password"  placeholder="需重置密码时输入"/>
        </el-form-item>
        <el-form-item label="重复密码" prop="title">
          <el-input v-model="temp.password2"  placeholder="需重置密码时输入"/>
        </el-form-item>
        <el-form-item label="角色" prop="title">
          <el-select v-model="myRoleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, fetchPv, createUser, updateUser, removeUser} from './api/user'
import waves from '@/directive/waves' // waves directive
import {parseTime, resizeTableHeight} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {getList} from './api/role'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
    name: 'UserList',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
              page: 1,
              limit: 20,
              name: undefined,
              loginname: undefined,
              sort: '-id'
            },
            importanceOptions: [1, 2, 3],
            calendarTypeOptions,
            sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
            statusOptions: ['published', 'draft', 'deleted'],
            showReviewer: false,
            temp: {
              id: undefined,
              name: '',
              loginname: '',
              deleteflag: '1',
              password: '',
              password2: ''
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
              update: '编辑',
              create: '新增'
            },
            dialogPvVisible: false,
            pvData: [],
            rules: {
              name: [{ required: true, message: 'name is required', trigger: 'blur' }],
              loginname: [{ required: true, message: 'loginname is required', trigger: 'blur' }]
            },
            downloadLoading: false,
            roles: [],
            myRoleIds: [],
            // control table height dynamic
            tableHeight:0, // 表格高度
            filterContainerHeight: 0, // 查询容器高度
            clientHeight: 0, // 浏览器高度
        }
    },
    created() {
        this.getList()
        // 浏览器、元素大小变化时，动态调整table高度
    },
    mounted() {
        resizeTableHeight(this)
    },
    methods: {
        getList() {
          this.listLoading = true
          fetchList(this.listQuery).then(result => {
            this.list = result.map.rows
            this.total = result.map.total

            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 0.1 * 1000)

            // get role list
            getList().then(result => {
              this.roles = result.list
            })
          })
        },
        handleFilter() {
          this.listQuery.page = 1
          this.getList()
        },
        sortChange(data) {
          const { prop, order } = data
          if (prop === 'id') {
            this.sortByID(order)
          }
        },
        sortByID(order) {
          if (order === 'ascending') {
            this.listQuery.sort = '+id'
          } else {
            this.listQuery.sort = '-id'
          }
          this.handleFilter()
        },
        resetTemp() {
          this.temp = {
            name: '',
            loginname: '',
            deleteflag: '1',
            password: ''
          }
          this.myRoleIds = []
        },
        handleCreate() {
          this.resetTemp()
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          /* this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })*/
        },
        createData() {
          const param = Object.assign({}, this.temp)
          param.roleIds = '' + this.myRoleIds
          createUser(param).then((result) => {
              this.notify(r)
              if (r.success) {
                  this.dialogFormVisible = false
                  this.handleFilter()
              }
          })
        },
        handleUpdate(row) {
          this.temp = Object.assign({}, row) // copy obj
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          if (this.temp.roleIds) {
            this.myRoleIds = this.temp.roleIds.split(',').map(Number)
          } else {
            this.myRoleIds = []
          }
          /* this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })*/
        },
        updateData() {
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              const param = Object.assign({}, this.temp)
              param.roleIds = '' + this.myRoleIds
              updateUser(param).then((r) => {
                  this.notify(r)
                  if (r.success) {
                      this.dialogFormVisible = false
                      this.getList()
                  }
              })
            }
          })
        },
        handleDelete(row, index) {
          const param = {}
          param.id = row.id
          removeUser(param).then(() => {
              this.notify(r)
              if (r.success) {
                  this.getList()
              }
          })
        },
        handleFetchPv(pv) {
          fetchPv(pv).then(response => {
            this.pvData = response.data.pvData
            this.dialogPvVisible = true
          })
        },
        handleDownload() {
          this.downloadLoading = true
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
            const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
            const data = this.formatJson(filterVal)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'table-list'
            })
            this.downloadLoading = false
          })
        },
        formatJson(filterVal) {
          return this.list.map(v => filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          }))
        },
        getSortClass: function(key) {
          const sort = this.listQuery.sort
          return sort === `+${key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
<style>

</style>
